package com.springboot.jdk.nio;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * FileChannel Lock 案例
 *
 * @author: zr
 * @date: 2021-10-19
 */
public class FileChannelShareLockDemo {

    public static void main(String[] args) throws IOException, InterruptedException {
        String path = "F:\\develop\\channel\\hello.txt";

        // 构造一个传统的文件输入流
        FileInputStream fileInputStream = new FileInputStream(path);

        // 通过文件输出流获取到对应的FileChannel, 已NIO的方式来写文件
        FileChannel channel = fileInputStream.getChannel();

        // true 表示加了一把共享锁
        // false 表示加了一把独占锁
        channel.lock(0, Integer.MAX_VALUE, true);
        System.out.println("加锁成功");
        Thread.sleep(60 * 60 * 1000);

        channel.close();
        fileInputStream.close();
    }
}
